package my.spider;

import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.pipeline.FilePipeline;
import us.codecraft.webmagic.pipeline.JsonFilePipeline;
import us.codecraft.webmagic.processor.PageProcessor;
import us.codecraft.webmagic.processor.example.GithubRepoPageProcessor;

/**
 * Created by user on 2016/2/29.
 */
public class WebMagicExamplePageProcessor implements PageProcessor {
    private Site site = Site.me().setRetryTimes(3).setSleepTime(100);
    @Override
    public void process(Page page) {http://www.javaworld.com/article/3030214/big-data/open-source-java-projects-apache-phoenix.html
        page.addTargetRequests(page.getHtml().links().regex("(http://www\\.javaworld\\.com/article/\\d{7}/[\\w\\-]+/[\\w\\-]+.html)").all());
        page.putField("author", page.getHtml().xpath("//span[@itemprop='name']/text()").toString());
        page.putField("date",page.getHtml().xpath("//span[@itemprop='datePublished']/text()").toString());
        page.putField("title", page.getHtml().xpath("//h1[@itemprop='headline']/text()").toString());
        page.putField("content",page.getHtml().xpath("//div[@itemprop='articleBody']/tidyText()")/*.regex("(?<=<p>)[\\s\\S]*?(?=</p>)",0).all().toString()*/);
        if (page.getResultItems().get("title")==null){
            //skip this page
            page.setSkip(true);
        }

    }

    @Override
    public Site getSite() {
        return site;
    }

    public static void main(String[] args) {
        Spider.create(new WebMagicExamplePageProcessor()).
                addUrl("http://www.javaworld.com/blog/open-source-java-projects/")
                .addPipeline(new FilePipeline("D:\\webmagic\\"))
                .thread(10).run();
    }

}
